//
//  Me.swift
//  CreateMyCode
//
//  Created by zhibao on 2024/2/1.
//

import UIKit
class MeController:SuperController,UITableViewDelegate,UITableViewDataSource,UIDocumentInteractionControllerDelegate {
    var vipTitleLabel:UILabel!
    var vipDetailLabel:UILabel!
    var showTableView:MYTableView!
    var dataArray:[[[String:String]]]!
    fileprivate var document:UIDocumentInteractionController!
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        let pingFlag = DWKeychainTool.getItemForKey("haoping")
        if (MYGlobal.share().wechatFlag != 1){
            if pingFlag == nil {
                dataArray = [
                    [
                       [ "name":LocalizedString("五星好评"),"img":"figure.cricket","detail":LocalizedString("获得7天Vip")],
                       [ "name":LocalizedString("关于我们"),"img":"pencil.circle"],
                       [ "name":LocalizedString("联系我们"),"img":"megaphone"],
                       [ "name":LocalizedString("分享好友"),"img":"square.and.arrow.up"]
                    ],
                    [
                       [ "name":LocalizedString("用户协议"),"img":"paperplane"],
                       [ "name":LocalizedString("隐私协议"),"img":"paperplane"],
                       [ "name":LocalizedString("订阅协议"),"img":"paperplane"],
                    ]
                ]
            }else{
                dataArray = [
                    [
                       [ "name":LocalizedString("关于我们"),"img":"pencil.circle"],
                       [ "name":LocalizedString("联系我们"),"img":"megaphone"],
                       [ "name":LocalizedString("分享好友"),"img":"square.and.arrow.up"]
                    ],
                    [
                       [ "name":LocalizedString("用户协议"),"img":"paperplane"],
                       [ "name":LocalizedString("隐私协议"),"img":"paperplane"],
                       [ "name":LocalizedString("订阅协议"),"img":"paperplane"],
                    ]
                ]
            }
            
        }else{
            dataArray = [
                [
                   [ "name":LocalizedString("关于我们"),"img":"pencil.circle"],
                   [ "name":LocalizedString("联系我们"),"img":"megaphone"],
                   [ "name":LocalizedString("分享好友"),"img":"square.and.arrow.up"]
                ],
                [
                   [ "name":LocalizedString("用户协议"),"img":"paperplane"],
                   [ "name":LocalizedString("隐私协议"),"img":"paperplane"],
                   [ "name":LocalizedString("订阅协议"),"img":"paperplane"],
                ]
            ]
        }
        if UserInfoManager.shared().isVip() {
            vipTitleLabel.text = LocalizedString("尊贵的VIP,您好！")
            let  data = DWKeychainTool.getItemForKey("vip") ?? "--"
            vipDetailLabel.text = "\(LocalizedString("有效期至："))\(data)"
        }else{
            vipTitleLabel.text = LocalizedString("点击开通VIP >")
            vipDetailLabel.text = LocalizedString("**所有功能都可使用**")
        }
        self.showTableView.reloadData()
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.gk_navTitle = LocalizedString("个人中心")
        dataArray = [
            [
               [ "name":LocalizedString("关于我们"),"img":"pencil.circle"],
               [ "name":LocalizedString("联系我们"),"img":"megaphone"]
            ],
            [
               [ "name":LocalizedString("用户协议"),"img":"paperplane"],
               [ "name":LocalizedString("隐私协议"),"img":"paperplane"],
               [ "name":LocalizedString("订阅协议"),"img":"paperplane"],
            ]
        ]
        self.initTableView()
    }
    
    fileprivate func createHeadView() -> UIView{
        let headView = UIView(frame: CGRect(x: 0, y: 0, width: SCREEN_WIDTH, height: pixw(p: 45 + 15) + pixw(p: 100) - pixw(p: 20) + pixw(p: 10)))
        let imgView = UIImageView(image: UIImage(named: "top_bg"))
        imgView.isUserInteractionEnabled = true
        imgView.layer.cornerRadius = pixw(p: 20)
        imgView.clipsToBounds = true
        imgView.layer.masksToBounds = true
        imgView.addGestureRecognizer(UITapGestureRecognizer(actionBlock: { sender in
            let controller = PayMarkController()
            self.navigationController?.pushViewController(controller, animated: true)
        }))
        headView.addSubview(imgView)
        imgView.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 15))
            make.top.equalTo(pixw(p: 20))
            make.right.equalTo(pixw(p: -15))
            make.height.equalTo(pixw(p: 100))
        }
        
        vipTitleLabel = UILabel()
        vipTitleLabel.text = LocalizedString("点击开通VIP >")
        vipTitleLabel.font = MY_SCALE_LightFONT(20)
        vipTitleLabel.textAlignment = .center
        vipTitleLabel.numberOfLines = 0
        vipTitleLabel.lineBreakMode = .byWordWrapping
        vipTitleLabel.textColor = MYOrange
        imgView.addSubview(vipTitleLabel)
        vipTitleLabel.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 23))
            make.right.equalTo(pixw(p: -23))
            make.top.equalTo(pixw(p: 16))
        }
        
        vipDetailLabel = UILabel()
        vipDetailLabel.text = LocalizedString("**所有功能都可使用**")
        vipDetailLabel.font = MY_SCALE_LightFONT(14)
        vipDetailLabel.textAlignment = .center
        vipDetailLabel.numberOfLines = 0
        vipDetailLabel.lineBreakMode = .byWordWrapping
        vipDetailLabel.textColor = MYOrange
        imgView.addSubview(vipDetailLabel)
        vipDetailLabel.snp.makeConstraints { make in
            make.left.equalTo(pixw(p: 23))
            make.right.equalTo(pixw(p: -23))
            make.top.equalTo(imgView.snp.centerY).offset(pixw(p: 3))
        }
        return headView
    }
    
    fileprivate func initTableView(){
        showTableView = MYTableView(frame: CGRect(x: 0, y: navigationFullHeight(), width: SCREEN_WIDTH, height: SCREEN_HEIGHT - navigationFullHeight()), style: .grouped)
        showTableView.backgroundColor = MYColor.color(withHexString: "ffffff")
        showTableView.delegate = self
        showTableView.dataSource = self
        showTableView.separatorStyle = .none
        showTableView.tableHeaderView = self.createHeadView()
        showTableView.removeMJRefresh()
        showTableView.register(MeCell.self, forCellReuseIdentifier: "mecell")
        self.view.addSubview(showTableView)
        showTableView.reloadData()
        showTableView.nodataView.removeFromSuperview()
    }
}

extension MeController{
    func numberOfSections(in tableView: UITableView) -> Int {
        return dataArray.count
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataArray[section].count
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return pixw(p: 5)
        }else if section == 1 {
            return pixw(p: 5)
        }
        return 0.00001
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell = tableView.dequeueReusableCell(withIdentifier: "mecell") as! MeCell
        cell.updata(dic: dataArray[indexPath.section][indexPath.row])
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let title = dataArray[indexPath.section][indexPath.row]["name"]
        if title == LocalizedString("五星好评") {
            let urlStr = "itms-apps://itunes.apple.com/app/id6478015472?action=write-review"
            UIApplication.shared.open(URL(string: urlStr)!,options: [:]) { flag in
                let time = Helper.getTime(.day)
                QMUITips.showSucceed(LocalizedString("...评论成功..."), detailText: LocalizedString("...恭喜您成为Vip会员..."))
                DWKeychainTool.saveItem("day", key: "id")
                DWKeychainTool.saveItem(time, key: "vip")
                DWKeychainTool.saveItem("haoping", key: "haoping")
                UserInfoManager.shared().getUserInfoData { sucess in
                    self.viewWillAppear(true)
                }
            }
        }
        else if title == LocalizedString("关于我们") {
            let controller = AboutMeController()
            self.navigationController?.pushViewController(controller, animated: true)
        }else if title == LocalizedString("联系我们") {
            let controller = CallMeController()
            self.navigationController?.pushViewController(controller, animated: true)
        }else if title == LocalizedString("分享好友") {
            document = UIDocumentInteractionController(url:NSURL(string: "https://apps.apple.com/cn/app/%E4%BA%8C%E7%BB%B4%E7%A0%81%E5%88%B6%E4%BD%9C%E5%8A%A9%E6%89%8B-div%E5%A4%9A%E6%A0%B7%E5%BC%8F%E7%94%9F%E6%88%90%E5%AE%9E%E7%94%A8%E5%B7%A5%E5%85%B7/id6478015472")! as URL)
            document.delegate = self
            let _ = self.document.presentOptionsMenu(from: self.view.bounds, in: self.view, animated: true)
        }else if title == LocalizedString("用户协议") {
            let controller = WebViewController(title: LocalizedString("用户协议"), withUrl: "https://docs.qq.com/doc/DRmNvbVFaZm9LVG9t")
            self.navigationController?.pushViewController(controller, animated: true)
        }else if title == LocalizedString("隐私协议") {
            let controller = WebViewController(title: LocalizedString("隐私协议"), withUrl: "https://docs.qq.com/doc/DRnhXbWpia3dHV0R5")
            self.navigationController?.pushViewController(controller, animated: true)
        }else if title == LocalizedString("订阅协议") {
            let controller = WebViewController(title: LocalizedString("订阅协议"), withUrl: "https://docs.qq.com/doc/DRmx1SmpBb1BHbFZp")
            self.navigationController?.pushViewController(controller, animated: true)
        }
    }
    
    func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        
        let radius = 10
        cell.backgroundColor = UIColor.clear
        let normalLayer = CAShapeLayer()
        let selectLayer = CAShapeLayer()
        
        let bounds = CGRectInset(cell.bounds, SCREEN_WIDTH / 375 * 14, 0)
        
        let normalBgView = UIView(frame: bounds)
        let rowNum = tableView.numberOfRows(inSection: indexPath.section)
        var beziePath:UIBezierPath?
        
        if rowNum == 1 {
            beziePath = UIBezierPath(roundedRect: bounds, byRoundingCorners: .allCorners, cornerRadii: CGSize(width: radius, height: radius))
            normalBgView.clipsToBounds = false
        }else{
            normalBgView.clipsToBounds =  true
            if indexPath.row == 0 {
                normalBgView.frame = CGRectInsetEdges(bounds, UIEdgeInsets(top: -5, left: 0, bottom: 0, right: 0))
                beziePath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.topLeft ,.topRight], cornerRadii: CGSize(width: radius, height: radius))
            }else if indexPath.row == rowNum - 1 {
                normalBgView.frame = CGRectInsetEdges(bounds, UIEdgeInsets(top: 0, left: 0, bottom: -5, right: 0))
                beziePath = UIBezierPath(roundedRect: bounds, byRoundingCorners: [.bottomLeft ,.bottomRight], cornerRadii: CGSize(width: radius, height: radius))
            }else{
                beziePath = UIBezierPath(rect: bounds)
            }
        }
        
        normalLayer.shadowColor = MYColor.color(withHexString: "#35393F", alpha: 0.6).cgColor
        normalLayer.shadowOpacity = 0.2
        normalLayer.shadowOffset = CGSizeMake(1, 1)
        normalLayer.shadowPath = beziePath?.cgPath
        
        normalLayer.path = beziePath?.cgPath
        selectLayer.path = beziePath?.cgPath
        
        normalLayer.fillColor = MYColor.color(withHexString: "#ffffff", alpha: 0.6).cgColor
        normalBgView.layer.insertSublayer(normalLayer, at: 0)
        normalBgView.backgroundColor = UIColor.clear
        cell.backgroundView = normalBgView
    }
}

extension MeController{
    
    func documentInteractionControllerViewControllerForPreview(_ controller: UIDocumentInteractionController) -> UIViewController {
        return self
    }
    
    func documentInteractionControllerViewForPreview(_ controller: UIDocumentInteractionController) -> UIView? {
        return self.view
    }
    
    func documentInteractionControllerRectForPreview(_ controller: UIDocumentInteractionController) -> CGRect {
        return self.view.frame
    }
    
    func documentInteractionControllerDidDismissOpenInMenu(_ controller: UIDocumentInteractionController) {
        DLog(message: "disMiss")
    }
}
